package com.zziq.cloudpicturebank.manager.upload.templateImpl;

import cn.hutool.core.io.FileUtil;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.manager.upload.template.PictureUploadTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName FilePictureUpload
 * @Description 文件上传
 * @Created by ZZIQ
 **/
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    /**
     * @param inputSourse
     * @param file
     * @throws IOException
     */
    @Override
    protected void processFile(Object inputSourse, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile)inputSourse;
        multipartFile.transferTo(file);
    }

    /**
     * 获取文件原始名称
     * @param inputSourse
     * @return
     */
    @Override
    protected String getOriginalFilename(Object inputSourse) {
        MultipartFile multipartFile = (MultipartFile)inputSourse;
        return multipartFile.getOriginalFilename();
    }

    /**
     * 校验图片合法性
     * @param inputSourse
     */
    @Override
    protected String validPicture(Object inputSourse) {
        MultipartFile multipartFile = (MultipartFile)inputSourse;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
        return fileSuffix;
    }
}
